package ru.bragnikita.utils.test.nio;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;

public class ParallelReadWrite {

    public static void main(String[] args) throws IOException, InterruptedException {
	    final File directory = new File(".iotest");
	    FileUtils.forceMkdir(directory);
	    FileUtils.cleanDirectory(directory);
	    final File targetFile = new File(".iotest/logfile.txt");
	    if (targetFile.exists())
		    targetFile.delete();
	    targetFile.createNewFile();
	    Thread writeThread = new Thread(new Runnable() {
		    @Override
		    public void run() {
			    FileWriter writer = null;
			    try {
				    writer = new FileWriter(targetFile, true);
				    int recordNumber = 0;
			        while (!Thread.interrupted()) {
				        writer.write("Record #" + recordNumber + "\n");
				        recordNumber++;
				        writer.flush();
				        Thread.sleep(1000l);
			        }
			    } catch (IOException e) {
				    e.printStackTrace();
			    } catch (InterruptedException e) {
				    System.err.println("Writer was interrupted");
			    } finally {
				    IOUtils.closeQuietly(writer);
			    }
			}
	    }, "Writer");
	    Thread readThread = new Thread(new Runnable() {
		    @Override
		    public void run() {
			    FileReader reader = null;
			    try {
				    reader = new FileReader(targetFile);
				    BufferedReader bufferedReader = new BufferedReader(reader, 100);
				    while (!Thread.interrupted()) {
					    String newLine = bufferedReader.readLine();
					    System.out.println("New line: " + newLine);
					    Thread.sleep(500l);
				    }
			    } catch (FileNotFoundException e) {
				    e.printStackTrace();
			    } catch (InterruptedException ie) {
				    System.err.println("Reader was interrupted");
			    } catch (IOException e) {
				    e.printStackTrace();
			    } finally {
				    IOUtils.closeQuietly(reader);
			    }
			}
	    }, "Reader");
	    writeThread.start();
	    readThread.start();
	    Thread.sleep(10000l);
	    writeThread.interrupt();
	    readThread.interrupt();
    }
}
